<?php

namespace Act\Logic\Event;

use Act\Logic\Event\CallBackInterface;
use \common\Table\InputClick\AdClickQianluTable;
use \common\Table\InputClick\QianluEffectiveClickTable;
use \common\Factory\Factory;
use \core\data\partitionTable;

class QianluCallback implements CallBackInterface {
    
    private function selectQianluByIdfa($appid, $idfa, $eventTimestamp, $tableNum) {
        $config = \core\init\init::getConfig();
        $maxSecond = $config['actMaxSecond'];
        $adClickQianluTable = new AdClickQianluTable();
        $result = $adClickQianluTable->selectByIdfa($appid, $idfa, $eventTimestamp, $maxSecond, $tableNum);

        return $result === false ? false : $result;
    }
    
    public function actChange($appid, $idfa, $eventTimestamp) {
        $partitionTable = new partitionTable();

        strlen($eventTimestamp) == 13 && $eventTimestamp = substr($eventTimestamp, 0, 10);
        $tableNum = $partitionTable->getHashTable($idfa);
        //查询此次激活是否是有效激活（点击后1个月内激活为有效激活）
        $queryIdfaResult = $this->selectQianluByIdfa($appid, $idfa, $eventTimestamp, $tableNum);
        $result = false;
        if($queryIdfaResult !== false) {
            $qianluEffectiveClickTable = new QianluEffectiveClickTable();
            //查询数据是否已存在
            $effectiveSelectResult = $qianluEffectiveClickTable->selectByIdfaAndAppId($idfa, $appid);
            if($effectiveSelectResult === false) {
                $effectiveResult = $qianluEffectiveClickTable->insertEffectiveQianlu(array('idfa' => $idfa, 'appid' => $appid, 'click_timestamp' => $queryIdfaResult['input_timestamp'], 'act_timestamp' => $eventTimestamp, 'time' => date('Ym', $queryIdfaResult['input_timestamp'])));
                if($effectiveResult === true) {
                    $result = true;
                    Factory::getServer('MqWriteLog')->send('act insert database qianlu effective and collect success');
                }
                else {
                    Factory::getServer('MqWriteLog')->send('act insert database qianlu effective failed');
                }
            }
            else {
                $result = true;
                Factory::getServer('MqWriteLog')->send('act insert database qianlu effective appid:'. $appid .' idfa:'. $idfa .' is exists');
            }
        }
        else {
            $result = true;
        }
        
        return $result;
    }
}